package sft.Autenticacao.Login;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import sft.Autenticacao.Login.Logica.Login;
import sft.BancodeDados.CriaConexao;

public class LoginDao {
    
    private Connection conexao;

    public LoginDao() {
        try {
            this.conexao = new CriaConexao().getConnection();
        } catch (SQLException ex) {
            System.out.println("Erro DAO LOGIN");
            Logger.getLogger(LoginDao.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void Operacao(Login l){
        try {
            try (PreparedStatement stmt = conexao.prepareStatement(l.getSql())) {
                setSTMT(stmt, l);
                stmt.execute();
                stmt.close();
            }
        } catch (SQLException ex) {
            Logger.getLogger(LoginDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
    }

    private void setSTMT(PreparedStatement stmt, Login l) throws SQLException {
        switch(l.getOperacao()){
            case "adicionar":
                setPrincipal(stmt, l);
                break;
            case "editar":
                setPrincipal(stmt, l);
                stmt.setInt(4, l.getId());
                break;
            case "deletar":
                stmt.setInt(1, l.getId());
                break;
        }
    }

    private void setPrincipal(PreparedStatement stmt, Login l) throws SQLException {
        stmt.setString(1, l.getNome());
        stmt.setString(2, l.getSenha());
        stmt.setInt(3, l.getPerfil());
    }
    
    public List<Login> getList(Login l, boolean nome) {
        try {
            ResultSet rs;
            List<Login> list;
            try (PreparedStatement stmt = conexao.prepareStatement(l.getSql())) {
                if(nome){
                    stmt.setString(1, "%" + l.getNome() + "%");
                }
                rs = stmt.executeQuery();
                list = new ArrayList<>();
                while(rs.next()){
                    Login a = new Login();
                    a.setId(rs.getInt(1));
                    a.setNome(rs.getString(2));
                    a.setSenha(rs.getString(3));
                    a.setPerfil(rs.getInt(4));
                    list.add(a);   
                }
            }
            rs.close();
            
            return list;
        } catch (SQLException ex) {
            System.out.println("ERRO NA PERSQUISA");
            Logger.getLogger(LoginDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}
